package com.cz.fra.android.logic;

import java.util.ArrayList;
import java.util.List;

import com.cz.fra.android.data.FishReport.LocationTable;
import com.cz.fra.android.entity.Location;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class LocationLogic {

	private static LocationLogic instance;
	
	private ContentResolver cr;

	private Context mContext;
	
	private LocationLogic(Context context) {
		mContext = context;
		cr = mContext.getContentResolver();
	}
	
	public static LocationLogic getInstance(Context context) {
		if (instance == null) {
			instance = new LocationLogic(context);
		}
		return instance;
	}
	
	public synchronized void insertLocations(ArrayList<Location> list) {
		if (cr == null) {
			cr = mContext.getContentResolver();
		}

		int length = list.size();
		Log.e("insertLocationList start", System.currentTimeMillis() + "");
		ContentValues[] values = new ContentValues[length];
		for (int i = 0; i < length; i++) {
			Location l = list.get(i);
			values[i] = l.instanceToCV();
		}
		cr.bulkInsert(LocationTable.CONTENT_URI, values);
		synchronized (list) {
			list.clear();
		}
		Log.e("insertLocations end", System.currentTimeMillis() + "");
	}
	
	public List<Location> getLocations(){
		if (cr == null) {
			cr = mContext.getContentResolver();
		}
		ArrayList<Location> arrayList = new ArrayList<Location>();
		Cursor cursor = cr.query(LocationTable.CONTENT_URI, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				Location l = new Location();
				l.setLocation(cursor.getString(cursor.getColumnIndex(LocationTable.LOCATION)));
				l.setDescription(cursor.getString(cursor.getColumnIndex(LocationTable.DESCRIPTION)));
				arrayList.add(l);
			}while (cursor.moveToNext());
		}
		cursor.close();
		return arrayList;
		
	}
}
